package com.jungle.mvvm.sample.http;

import com.jungle.mvvm.utils.SPUtils;
import com.jungle.mvvm.utils.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @ClassName CookieInterceptor
 * @Description cookie拦截器
 * @Author Daniel
 * @Version V1.0.0
 */
public class CookieInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request()
                .newBuilder();
        String userId = SPUtils.getInstance().getString("userId");
        if (!StringUtils.isTrimEmpty(userId)) {
            HashMap<String, String> cookies = new HashMap<>(2);
            cookies.put("loginUserName", SPUtils.getInstance().getString("userName"));
            cookies.put("loginUserPassword", SPUtils.getInstance().getString("password"));

            if (cookies.size() > 0) {
                StringBuilder sb = new StringBuilder();
                Set<String> keys = cookies.keySet();
                for (String headerKey : keys) {
                    sb.append(headerKey).append("=").append(cookies.get(headerKey)).append(";");
                }
                builder.addHeader("Cookie", sb.toString()).build();
            }
        }
        //请求信息
        return chain.proceed(builder.build());
    }
}